<template>
  <div class="bi-category-main">
    <je-panel v-bind="options">
      <!-- 顶部按钮 -->
      <template #tbar>
        <div class="operate-box">
          <je-tooltip placement="bottom">
            <template #title>
              <span>新建模块</span>
            </template>
            <je-button
              type="text"
              size="small"
              :disabled="btnDisabled.module"
              @click="handleTopBtn('module')"
            >
              <template #icon>
                <i class="fal fa-folder-plus"></i>
              </template>
            </je-button>
          </je-tooltip>
          <je-tooltip placement="bottom">
            <template #title>
              <span>新建数据源</span>
            </template>
            <je-button
              type="text"
              size="small"
              :disabled="btnDisabled.source"
              @click="handleTopBtn('source')"
            >
              <template #icon>
                <i class="fal fa-database"></i>
              </template>
            </je-button>
          </je-tooltip>
          <je-tooltip placement="bottom">
            <template #title>
              <span>删除</span>
            </template>
            <je-button
              type="text"
              size="small"
              :disabled="btnDisabled.remove"
              @click="handleTopBtn('remove')"
            >
              <template #icon>
                <i class="fal fa-trash-alt"></i>
              </template>
            </je-button>
          </je-tooltip>
          <je-tooltip placement="bottom">
            <template #title>
              <span>复制</span>
            </template>
            <je-button
              type="text"
              size="small"
              :disabled="btnDisabled.copy"
              @click="handleTopBtn('copy')"
            >
              <template #icon>
                <i class="fal fa-copy"></i>
              </template>
            </je-button>
          </je-tooltip>
          <je-tooltip placement="bottom">
            <template #title>
              <span>收起</span>
            </template>
            <je-button type="text" size="small" @click="handleTopBtn('packUp')">
              <template #icon>
                <i class="jeicon jeicon-packup"></i>
              </template>
            </je-button>
          </je-tooltip>
        </div>
      </template>
      <!-- 数据源树 -->
      <template #default>
        <je-tree
          ref="treeview"
          class="table-treeView"
          draggable
          :search="{ style: 'height:40px;' }"
          :tree-config="{
            trigger: 'cell-dblclick',
            rowField: 'id',
            parentField: 'parent',
          }"
          size="mini"
          :data="sourceTree"
          @current-change="handlerSelect"
          @before-drop="handleBeforeDrop"
          @drop="handleDrop"
          @search-select="handldSearch"
        >
          <template #nodeIcon="{ row }">
            <template v-if="row.nodeInfo === 'MODULE'">
              <i style="color: #ffba3d" class="fas fa-folder"></i>
            </template>
            <template v-if="row.nodeInfo === sourceObj.viewType">
              <i :class="sourceObj.viewIcon"></i>
            </template>
            <template v-if="row.nodeInfo === sourceObj.sqlType">
              <i :class="sourceObj.sqlIcon"></i>
            </template>
            <template v-if="row.nodeInfo === sourceObj.jsType">
              <i :class="sourceObj.jsIcon"></i>
            </template>
            <template v-if="row.nodeInfo === sourceObj.actionType">
              <i :class="sourceObj.actionIcon"></i>
            </template>
            <template v-if="row.nodeInfo === sourceObj.serviceType">
              <i :class="sourceObj.serviceIcon"></i>
            </template>
            <template v-if="row.nodeInfo === sourceObj.tableType">
              <i :class="sourceObj.tableIcon"></i>
            </template>
          </template>
          <template #action="options">
            <je-menu
              v-if="options.row.nodeInfo === 'MODULE'"
              @click="({ key: menuKey }) => handleModuleBtn(menuKey, options)"
            >
              <je-menu-item key="module">
                <i style="font-size: 14px; margin-right: 10px" class="fal fa-folder-plus" />
                {{ $t('sourceModel.createModule') }}
              </je-menu-item>
              <je-menu-item key="source">
                <i style="font-size: 14px; margin-right: 10px" class="fal fa-database" />
                {{ $t('sourceModel.createSource') }}
              </je-menu-item>
              <je-menu-item key="edit">
                <i style="font-size: 14px; margin-right: 7px" class="fal fa-file-edit" />
                {{ $t('sourceModel.editModule') }}
              </je-menu-item>
              <je-menu-item key="delete" :disabled="options.row.children.length > 0">
                <i style="font-size: 14px; margin-right: 10px" class="fal fa-trash-alt" />
                {{ $t('sourceModel.deleteModule') }}
              </je-menu-item>
            </je-menu>
            <je-menu
              v-if="options.row.nodeInfo !== 'MODULE'"
              @click="({ key: menuKey }) => handleSourceBtn(menuKey, options)"
            >
              <je-menu-item key="copy">
                <i style="font-size: 14px; margin-right: 8px" class="fal fa-copy" />
                {{ $t('sourceModel.copySource') }}
              </je-menu-item>
              <je-menu-item key="delete">
                <i style="font-size: 14px; margin-right: 10px" class="fal fa-trash-alt" />
                {{ $t('sourceModel.deleteSource') }}
              </je-menu-item>
            </je-menu>
          </template>
        </je-tree>
      </template>
      <!-- 产品分类列表 -->
      <template #bbar>
        <div class="category-footer">
          <je-dropdown :trigger="['click']" placement="top">
            <a class="ant-dropdown-link" @click.prevent>
              <i class="conditionicon fas fa-question-circle" @click="clickProductIcon" />
              {{ selectProduct.productName }}
              <i class="fal fa-angle-down"></i>
            </a>
            <template #overlay>
              <je-menu style="min-width: 240px; max-width: 400px" class="tabel-productMune">
                <je-menu-item v-for="productItem in productList" :key="productItem.productId">
                  <a @click="changeProduct(productItem)">{{ productItem.productName }}</a>
                </je-menu-item>
              </je-menu>
            </template>
          </je-dropdown>
        </div>
      </template>
    </je-panel>
  </div>
  <!-- 产品 -->
  <je-modal
    v-model:visible="visibleProduct"
    width="400"
    title="说明"
    height="auto"
    :resize="false"
    class="productinfo-modal"
    ok-button
    button-align="right"
    :maximizable="false"
  >
    <div>切换服务，维护对应服务中的数据源数据。</div>
  </je-modal>
  <!-- 新增模块 -->
  <modal-module
    v-if="editModule"
    :module-data="moduleData"
    :parent-id="sourceParentId"
    :product-id="selectProduct.productId"
    @loadSourceTree="loadSourceTree"
    @cancelEditModule="cancelEditModule"
  />
  <!-- 新增数据源 -->
  <modal-source
    v-if="editSource"
    :source-data="sourceData"
    :parent-id="sourceParentId"
    :product-id="selectProduct.productId"
    @loadTreeAndSelect="loadTreeAndSelect"
    @cancelEditSource="cancelEditSource"
  />
  <!-- 复制数据源 -->
  <modal-copy
    v-if="copySource"
    :source-data="copySourceData"
    :product-id="selectProduct.productId"
    @loadSourceTree="loadSourceTree"
    @cancelCopySource="cancelCopySource"
  />
</template>

<script>
  import { defineComponent, reactive, toRefs, ref, toRaw, onMounted, onUnmounted } from 'vue';
  import { Panel, Tree, Button, Dropdown, Menu, Modal } from '@jecloud/ui';
  import VueEvent from '@/helper/event';
  import ModalModule from '@/views/data-source/source-type/components/modal-module.vue';
  import ModalSource from '@/views/data-source/source-type/components/modal-source.vue';
  import ModalCopy from '@/views/data-source/source-type/components/modal-copy.vue';
  import { DataSource } from '@/views/data-source/model/data-source';
  import { useSourceStore } from '@/store/source-store';
  import { getCurrentUser } from '@jecloud/utils';
  import { treeToList } from '@/helper/public';
  import {
    SOURCE_TREE_SELECT,
    SOURCE_SELECT_TREE_NODE,
    SOURCE_TYPE_ICON,
    SOURCE_RELOAD_TREE,
    SOURCE_TREE_SELECT_OPEN,
    SOURCE_CLOSE_PANE,
    SOURCE_DELETE_SOURCE,
  } from '@/helper/constant';
  import {
    getProductData,
    getSourceTree,
    removeSourceAndModule,
    moveTree,
    getSourceDataById,
  } from '@/api';
  export default defineComponent({
    name: 'SourceType',
    components: {
      JePanel: Panel,
      JeTree: Tree,
      JeButton: Button,
      JeDropdown: Dropdown,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeModal: Modal,
      ModalModule,
      ModalSource,
      ModalCopy,
    },
    emits: ['changeSelectProduct'],
    setup(props, { emit }) {
      const sourceStore = useSourceStore(); //数据源全局状态
      const { deptmentUserId } = getCurrentUser(); //localstore中产品服务缓存的key
      const treeview = ref(null);
      const state = reactive({
        options: {
          top: { size: 40, split: false, minSize: 240 },
          tbar: { size: 40 },
          bbar: { size: 40 },
        },
        productList: [], //产品列表
        selectProduct: {}, //选中的产品信息
        visibleProduct: false, //数据源产品说明
        //模块
        moduleData: {
          id: '', //模块id
          name: '', //模块名称
          code: '', //模块编码
        },
        sourceParentId: '', //父节点id
        sourceParentType: '', //当前父节点类型
        curSourceName: '', //当前数据源名称
        editModule: false, //模块编辑
        //数据源
        sourceData: {
          id: '', //模块id
          name: '', //模块名称
          code: '', //模块编码
          type: 'TABLE', //类型
          remark: '', //备注
        },
        editSource: false, //数据源编辑
        copySource: false, //复制数据源
        //复制数据源
        copySourceData: {
          id: '', //模块id
          name: '', //模块名称
          code: '', //模块编码
        },
        sourceObj: SOURCE_TYPE_ICON, //数据源类型及对应icon
        //操作按钮只读状态
        btnDisabled: {
          module: false, //文件夹
          source: true, //数据源
          remove: true, //删除
          copy: true, //复制
        },
        //资源标结构树
        sourceTree: [],
      });
      const methods = {
        //获取产品数据列表
        getProductList() {
          getProductData({
            tableCode: 'JE_PRODUCT_MANAGE',
            funcCode: 'JE_PLATFORM_PRODUCT_MANAGE',
            j_query: JSON.stringify({ order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }] }),
            PRODUCT_ENABLE_STATE: '1',
          })
            .then((res) => {
              const menuDatas = [];
              res.rows.forEach((item) => {
                menuDatas.push({
                  productId: item.JE_PRODUCT_MANAGE_ID,
                  productName: item.PRODUCT_NAME,
                  productCode: item.PRODUCT_CODE,
                });
              });
              state.productList = menuDatas;
              //缓存中存在对应的产品服务
              const storeProductId = localStorage.getItem(deptmentUserId);
              if (storeProductId) {
                for (let productItem of state.productList) {
                  if (productItem.productId == storeProductId) {
                    state.selectProduct = productItem;
                    break;
                  }
                }
              } else {
                //若缓存中不存在，默认选中第一个
                state.selectProduct = menuDatas[0];
              }
              methods.getSourceTreeList(state.selectProduct.productId);
              // context.emit('getProductData', menuDatas[0]);
            })
            .catch((e) => {
              // Modal.alert(e.message, 'error');
            });
        },
        //产看产品服务说明
        clickProductIcon(event) {
          event.stopPropagation();
          state.visibleProduct = true;
        },
        //切换服务
        changeProduct(productItem) {
          if (productItem.productId == state.selectProduct.productId) {
            return;
          }
          //若产品发生改变，需更新缓存中数据
          localStorage.setItem(deptmentUserId, productItem.productId);
          state.selectProduct = productItem;
          methods.getSourceTreeList(state.selectProduct.productId);
          sourceStore.initSourceData();
          state.btnDisabled.module = false; //文件夹
          state.btnDisabled.source = true; //数据源
          state.btnDisabled.remove = true; //删除
          state.btnDisabled.copy = true; //复制
          emit('changeSelectProduct', productItem);
        },
        //根据产品id获取数据源结构树
        getSourceTreeList(productId) {
          const treeParam = {
            tableCode: 'JE_CORE_DATASOURCE',
            funcCode: 'JE_CORE_DATASOURCE',
            SY_PRODUCT_ID: productId,
          };
          getSourceTree(treeParam).then((res) => {
            state.sourceTree = res.children;
          });
        },
        //顶部按钮操作
        handleTopBtn(type) {
          switch (type) {
            case 'module': //新建文件夹
              state.moduleData = {
                id: '', //模块id
                name: '', //模块名称
                code: '', //模块编码
              };
              state.editModule = true;
              break;
            case 'source': //新建数据源
              state.sourceData = {
                id: '', //模块id
                name: '', //模块名称
                code: '', //模块编码
                type: 'TABLE', //类型
                remark: '', //备注
              };
              state.editSource = true; //数据源编辑
              break;
            case 'remove': //删除
              const curDeleteSourceCode = sourceStore.getSourceCode();
              const curDeleteSourceData = sourceStore.getSourceDataByCode(curDeleteSourceCode);
              Modal.confirm({
                title: '删除',
                content:
                  curDeleteSourceData.DATASOURCE_TYPE == 'MODULE'
                    ? `是否确认删除模块 ${state.curSourceName}？`
                    : `是否确认删除数据源 ${state.curSourceName}？`,
                okButton: () => {
                  const params = {
                    tableCode: 'JE_CORE_DATASOURCE',
                    funcCode: 'JE_CORE_DATASOURCE',
                    ids: curDeleteSourceData.JE_CORE_DATASOURCE_ID,
                  };
                  removeSourceAndModule(params).then((res) => {
                    if (res.success) {
                      Modal.notice({ content: '删除成功', status: 'success' });
                      methods.loadSourceTree();
                      state.sourceParentId = '';
                      state.sourceParentType = '';
                      state.curSourceName = ''; //当前数据源名称
                      VueEvent.emit(
                        SOURCE_DELETE_SOURCE,
                        curDeleteSourceData.JE_CORE_DATASOURCE_ID,
                      );
                      setTimeout(() => {
                        treeview.value.setSelectRow({});
                      }, 500);
                    } else {
                      Modal.alert(res.message, 'error');
                    }
                  });
                },
              });
              break;
            case 'copy': //复制
              const curSourceCode = sourceStore.getSourceCode();
              const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
              state.copySourceData = {
                id: curSourceData.JE_CORE_DATASOURCE_ID, //模块id
                name: curSourceData.DATASOURCE_TEXT, //模块名称
                code: curSourceData.DATASOURCE_CODE, //模块编码
              };
              state.copySource = true;
              break;
            case 'packUp': //收起
              treeview.value.clearTreeExpand();
              break;
            default:
              break;
          }
        },
        //重新加载树结构
        loadSourceTree() {
          methods.getSourceTreeList(state.selectProduct.productId);
        },
        //新增数据源后立即打开当前数据源
        loadTreeAndSelect(sourceData) {
          //父节点id
          state.sourceParentId = sourceData.JE_CORE_DATASOURCE_ID;
          state.sourceParentType = sourceData.DATASOURCE_TYPE;
          state.curSourceName = sourceData.DATASOURCE_TEXT; //当前数据源名称
          const treeParam = {
            tableCode: 'JE_CORE_DATASOURCE',
            funcCode: 'JE_CORE_DATASOURCE',
            SY_PRODUCT_ID: state.selectProduct.productId,
          };
          getSourceTree(treeParam).then((res) => {
            state.sourceTree = res.children;
            //不是文件夹的时候
            if (sourceData.DATASOURCE_TYPE != 'MODULE') {
              sourceStore.setSourceCode(sourceData.DATASOURCE_CODE);
              switch (sourceData.DATASOURCE_TYPE) {
                case state.sourceObj.viewType: //视图
                  sourceData.iconClass = state.sourceObj.viewIcon;
                  break;
                case state.sourceObj.sqlType: //sql
                  sourceData.iconClass = state.sourceObj.sqlIcon;
                  break;
                case state.sourceObj.jsType: //js
                  sourceData.iconClass = state.sourceObj.jsIcon;
                  break;
                case state.sourceObj.actionType: //视图
                  sourceData.iconClass = state.sourceObj.actionIcon;
                  break;
                case state.sourceObj.serviceType: //Service
                  sourceData.iconClass = state.sourceObj.serviceIcon;
                  break;
                case state.sourceObj.tableType: //table
                  sourceData.iconClass = state.sourceObj.tableIcon;
                  break;
              }
              //判断当前数据源是不在缓存中
              const curStoreSource = sourceStore.getSourceDataByCode(sourceData.DATASOURCE_CODE);
              if (!curStoreSource) {
                const curSource = new DataSource(sourceData);
                sourceStore.setSourceDataByCode(sourceData.DATASOURCE_CODE, curSource);
                // sourceStore.setRecoverSourceDataByCode(sourceData.DATASOURCE_CODE, curSource);
              }
              setTimeout(() => {
                const treeView = treeview.value;
                const row = treeView.getRowById(sourceData.JE_CORE_DATASOURCE_ID);
                if (row) {
                  methods.handlerSelect({ row, newValue: true });
                  treeView.setTreeExpand4Path({ row, expand: true }).then((row) => {
                    treeView.setSelectRow(row);
                    treeView.scrollToRow(row);
                  });
                }
                state.btnDisabled.module = true; //文件夹
                state.btnDisabled.source = true; //数据源
                state.btnDisabled.remove = false; //删除
                state.btnDisabled.copy = false; //复制
                state.curSourceName = sourceData.DATASOURCE_TEXT; //当前数据源名称
                VueEvent.emit(SOURCE_TREE_SELECT_OPEN, sourceData);
              }, 100);
            } else {
              state.btnDisabled.module = false; //文件夹
              state.btnDisabled.source = false; //数据源
              state.btnDisabled.remove = true; //删除
              state.btnDisabled.copy = true; //复制
            }
          });
        },
        //模块文件按钮
        handleModuleBtn(type, options) {
          if (options) {
            const { tooltip } = options;
            tooltip.visible = false;
          }
          switch (type) {
            case 'module': //新建文件夹
              state.sourceParentId = options.row.id;
              state.moduleData = {
                id: '', //模块id
                name: '', //模块名称
                code: '', //模块编码
              };
              state.editModule = true;
              break;
            case 'source': //新建数据源
              state.sourceParentId = options.row.id;
              state.sourceData = {
                id: '', //模块id
                name: '', //模块名称
                code: '', //模块编码
                type: 'TABLE', //类型
                remark: '', //备注
              };
              state.editSource = true;
              break;
            case 'edit': //编辑文件夹
              state.moduleData = {
                id: options.row.bean.JE_CORE_DATASOURCE_ID, //模块id
                name: options.row.bean.DATASOURCE_TEXT, //模块名称
                code: options.row.bean.DATASOURCE_CODE, //模块编码
              };
              state.editModule = true;
              break;
            case 'delete': //删除文件夹
              Modal.confirm({
                title: '删除',
                content: `是否确认删除文件夹 ${options.row.bean.DATASOURCE_TEXT}？`,
                okButton: () => {
                  const params = {
                    tableCode: 'JE_CORE_DATASOURCE',
                    funcCode: 'JE_CORE_DATASOURCE',
                    ids: options.row.id,
                  };
                  removeSourceAndModule(params).then((res) => {
                    if (res.success) {
                      Modal.notice({ content: '删除成功', status: 'success' });
                      methods.loadSourceTree();
                      //删除的文件是否和当前选中的相同
                      if (options.row.id == state.sourceParentId) {
                        state.sourceParentId = '';
                        state.sourceParentType = '';
                        state.curSourceName = ''; //当前数据源名称
                        state.btnDisabled.module = false; //文件夹
                        state.btnDisabled.source = true; //数据源
                        state.btnDisabled.remove = true; //删除
                        state.btnDisabled.copy = true; //复制
                        setTimeout(() => {
                          treeview.value.setSelectRow({});
                        }, 500);
                      }
                    } else {
                      Modal.alert(res.message, 'error');
                    }
                  });
                },
              });
              break;
            default:
              break;
          }
        },
        //数据源文件按钮
        handleSourceBtn(type, options) {
          if (options) {
            const { tooltip } = options;
            tooltip.visible = false;
          }
          switch (type) {
            case 'copy': //复制数据源
              state.copySourceData = {
                id: options.row.bean.JE_CORE_DATASOURCE_ID, //模块id
                name: options.row.bean.DATASOURCE_TEXT, //模块名称
                code: options.row.bean.DATASOURCE_CODE, //模块编码
              };
              state.copySource = true;
              break;
            case 'delete': //删除数据源
              Modal.confirm({
                title: '删除',
                content: `是否确认删除数据源 ${options.row.bean.DATASOURCE_TEXT}？`,
                okButton: () => {
                  const params = {
                    tableCode: 'JE_CORE_DATASOURCE',
                    funcCode: 'JE_CORE_DATASOURCE',
                    ids: options.row.id,
                  };
                  removeSourceAndModule(params).then((res) => {
                    if (res.success) {
                      Modal.notice({ content: '删除成功', status: 'success' });
                      VueEvent.emit(SOURCE_DELETE_SOURCE, options.row.id);
                      methods.loadSourceTree();
                      state.sourceParentId = '';
                      state.sourceParentType = '';
                      state.curSourceName = ''; //当前数据源名称
                      state.btnDisabled.module = false; //文件夹
                      state.btnDisabled.source = true; //数据源
                      state.btnDisabled.remove = true; //删除
                      state.btnDisabled.copy = true; //复制
                      // setTimeout(() => {
                      //   treeview.value.setSelectRow({});
                      // }, 500);
                    } else {
                      Modal.alert(res.message, 'error');
                    }
                  });
                },
              });
              break;
            default:
              break;
          }
        },
        //取消编辑模块弹窗
        cancelEditModule() {
          state.editModule = false;
        },
        //取消编辑数据源弹窗
        cancelEditSource() {
          state.editSource = false;
        },
        //取消复制数据源弹窗
        cancelCopySource() {
          state.copySource = false;
        },
        //选择当前数据源
        handlerSelect({ row }) {
          const curRow = toRaw(row);
          //没有选中节点
          if (!state.sourceParentId) {
            //父节点id
            state.sourceParentId = curRow.id;
            state.sourceParentType = curRow.nodeInfo;
            state.curSourceName = curRow.text; //当前数据源名称
            //不是文件夹的时候
            if (curRow.nodeInfo != 'MODULE') {
              sourceStore.setSourceCode(curRow.code);
              switch (curRow.nodeInfo) {
                case state.sourceObj.viewType: //视图
                  curRow.iconClass = state.sourceObj.viewIcon;
                  break;
                case state.sourceObj.sqlType: //sql
                  curRow.iconClass = state.sourceObj.sqlIcon;
                  break;
                case state.sourceObj.jsType: //js
                  curRow.iconClass = state.sourceObj.jsIcon;
                  break;
                case state.sourceObj.actionType: //视图
                  curRow.iconClass = state.sourceObj.actionIcon;
                  break;
                case state.sourceObj.serviceType: //Service
                  curRow.iconClass = state.sourceObj.serviceIcon;
                  break;
                case state.sourceObj.tableType: //table
                  curRow.iconClass = state.sourceObj.tableIcon;
                  break;
              }
              state.btnDisabled.module = true; //文件夹
              state.btnDisabled.source = true; //数据源
              state.btnDisabled.remove = false; //删除
              state.btnDisabled.copy = false; //复制
              //判断当前数据源是不在缓存中
              const curStoreSource = sourceStore.getSourceDataByCode(curRow.code);
              if (curStoreSource == undefined) {
                // getSourceDataById({ tableCode: 'JE_CORE_DATASOURCE', pkValue: curRow.id }).then(
                //   (res) => {
                //     if (res.success) {
                //       const curSource = new DataSource(res.data);
                //       sourceStore.setSourceDataByCode(res.data.DATASOURCE_CODE, curSource);
                //       // VueEvent.emit(SOURCE_TREE_SELECT, curRow);
                //     } else {
                //       Modal.alert(res.message, 'error');
                //     }
                //   },
                // );
                const curSource = new DataSource(curRow.bean);
                sourceStore.setSourceDataByCode(curRow.code, curSource);
              }
              VueEvent.emit(SOURCE_TREE_SELECT, curRow);
            } else {
              if (curRow.children.length > 0) {
                state.btnDisabled.module = false; //文件夹
                state.btnDisabled.source = false; //数据源
                state.btnDisabled.remove = true; //删除
                state.btnDisabled.copy = true; //复制
              } else {
                state.btnDisabled.module = false; //文件夹
                state.btnDisabled.source = false; //数据源
                state.btnDisabled.remove = false; //删除
                state.btnDisabled.copy = true; //复制
              }
            }
          } else {
            if (state.sourceParentId == curRow.id) {
              state.sourceParentId = '';
              state.btnDisabled.module = false; //文件夹
              state.btnDisabled.source = true; //数据源
              state.btnDisabled.remove = true; //删除
              state.btnDisabled.copy = true; //复制
            } else {
              //父节点id
              state.sourceParentId = curRow.id;
              state.sourceParentType = curRow.nodeInfo;
              state.curSourceName = curRow.text; //当前数据源名称
              //不是文件夹的时候
              if (curRow.nodeInfo != 'MODULE') {
                sourceStore.setSourceCode(curRow.code);
                switch (curRow.nodeInfo) {
                  case state.sourceObj.viewType: //视图
                    curRow.iconClass = state.sourceObj.viewIcon;
                    break;
                  case state.sourceObj.sqlType: //sql
                    curRow.iconClass = state.sourceObj.sqlIcon;
                    break;
                  case state.sourceObj.jsType: //js
                    curRow.iconClass = state.sourceObj.jsIcon;
                    break;
                  case state.sourceObj.actionType: //视图
                    curRow.iconClass = state.sourceObj.actionIcon;
                    break;
                  case state.sourceObj.serviceType: //Service
                    curRow.iconClass = state.sourceObj.serviceIcon;
                    break;
                  case state.sourceObj.tableType: //table
                    curRow.iconClass = state.sourceObj.tableIcon;
                    break;
                }
                state.btnDisabled.module = true; //文件夹
                state.btnDisabled.source = true; //数据源
                state.btnDisabled.remove = false; //删除
                state.btnDisabled.copy = false; //复制
                state.curSourceName = curRow.text; //当前数据源名称
                //判断当前数据源是不在缓存中
                const curStoreSource = sourceStore.getSourceDataByCode(curRow.code);
                if (curStoreSource == undefined) {
                  const curSource = new DataSource(curRow.bean);
                  sourceStore.setSourceDataByCode(curRow.code, curSource);
                  // sourceStore.setRecoverSourceDataByCode(curRow.code, curSource);
                }
                VueEvent.emit(SOURCE_TREE_SELECT, curRow);
              } else {
                if (curRow.children.length > 0) {
                  state.btnDisabled.module = false; //文件夹
                  state.btnDisabled.source = false; //数据源
                  state.btnDisabled.remove = true; //删除
                  state.btnDisabled.copy = true; //复制
                } else {
                  state.btnDisabled.module = false; //文件夹
                  state.btnDisabled.source = false; //数据源
                  state.btnDisabled.remove = false; //删除
                  state.btnDisabled.copy = true; //复制
                }
              }
            }
          }
        },
        selectTreeNode(data) {
          //选中对应树节点
          const treeView = treeview.value;
          const row = treeView.getRowById(data.id);
          if (row) {
            methods.handlerSelect({ row, newValue: true });
            treeView.setTreeExpand4Path({ row, expand: true }).then((row) => {
              treeView.setSelectRow(row);
              treeView.scrollToRow(row);
            });
          }
        },
        //左侧数据源树结构搜索
        handldSearch({ row }) {
          methods.handlerSelect({ row: row, newValue: true });
        },
        //数据源树开始拖拽之前
        handleBeforeDrop({ row, target, action }) {
          //数据源不能不在Root节点下拖动排序
          if (
            ['VIEW', 'JS', 'SQL', 'ACTION', 'SERVICE', 'TABLE'].includes(row.nodeInfo) &&
            target.parent == 'ROOT' &&
            action == 'sort'
          ) {
            return false;
          }
          //数据源下面不能添加任何节点
          if (
            ['VIEW', 'JS', 'SQL', 'ACTION', 'SERVICE', 'TABLE'].includes(target.nodeInfo) &&
            action == 'insert'
          ) {
            return false;
          }
        },
        handleDrop({ row, info, action }) {
          const params = {
            tableCode: 'JE_CORE_DATASOURCE',
            id: info.id,
            toId: '',
            place: '',
          };
          //如果拖拽在节点里面
          if (action == 'insert') {
            params.place = 'inside';
            params.toId = info.parentId;
          } else {
            //如果在节点的上面
            if (info.nextId != undefined) {
              params.place = 'above';
              params.toId = info.nextId;
            } else if (info.prevId != undefined) {
              params.place = 'below';
              params.toId = info.prevId;
            }
          }
          moveTree(params, { pd: 'meta' }).then((res) => {
            if (!res.success) {
              Modal.alert(res.message, 'error');
            }
          });
        },
        //监听pane关闭
        watchClosePane({ closePaneId, curPaneId }) {
          if (state.sourceParentId == closePaneId) {
            state.sourceParentId = '';
            state.btnDisabled.module = false; //文件夹
            state.btnDisabled.source = true; //数据源
            state.btnDisabled.remove = true; //删除
            state.btnDisabled.copy = true; //复制
            treeview.value.setSelectRow({});
          }
          //当前显示不为首页时
          if (curPaneId != 'index') {
            const treeList = treeToList(state.sourceTree);
            treeList.forEach((treeItem) => {
              if (treeItem.id == curPaneId) {
                state.sourceParentId = curPaneId;
                setTimeout(() => {
                  const treeView = treeview.value;
                  const row = treeView.getRowById(curPaneId);
                  if (row) {
                    methods.handlerSelect({ row, newValue: true });
                    treeView.setTreeExpand4Path({ row, expand: true }).then((row) => {
                      treeView.setSelectRow(row);
                      treeView.scrollToRow(row);
                    });
                  }
                }, 100);
              }
            });
          } else {
            treeview.value.setSelectRow({});
          }
        },
      };
      onMounted(() => {
        methods.getProductList();
        VueEvent.on(SOURCE_RELOAD_TREE, methods.loadSourceTree);
        VueEvent.on(SOURCE_SELECT_TREE_NODE, methods.selectTreeNode);
        VueEvent.on(SOURCE_CLOSE_PANE, methods.watchClosePane);
      });
      onUnmounted(() => {
        VueEvent.off(SOURCE_RELOAD_TREE);
        VueEvent.off(SOURCE_CLOSE_PANE);
      });
      return {
        treeview,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .bi-category-main {
    width: 100%;
    height: 100%;
    .operate-box {
      width: 100%;
      height: 40px !important;
      display: flex;
      align-items: center;
      justify-content: space-around;
      box-sizing: border-box;
      i {
        font-size: 16px;
        cursor: pointer;
      }
    }
  }
</style>
